<?php

namespace App\Http\Traits;

use finfo;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait FileUploadTrait
{
    public static function upload(UploadedFile $file, string $moduleName, string $folderName) {
        $fileName = time() . '_' . strtolower($file->getClientOriginalName());
        $path = $file->storeAs($moduleName . '/' . $folderName, $fileName);
        return $path;
    }

    public static function deleteFile(string $path) {
        return Storage::disk('public')->delete($path);
    }

    public static function getFile(string $path) {
        $tmp = explode('/', $path);
        $fileName = end($tmp);
        $filePath = public_path('storage/'. $path);
        $finfo = new finfo(FILEINFO_MIME_TYPE);

        if (Storage::disk('public')->exists($path)) {
            return new UploadedFile($filePath, $fileName, $finfo->file($filePath), filesize($filePath), 0, false);
        }
        return null;
    }
}
